package lv.solcraft.replication.server.boot;

import java.util.logging.Level;

import lv.solcraft.replication.server.rest.ReplicationServerApplication;

import org.apache.log4j.Logger;
import org.restlet.Component;
import org.restlet.data.Protocol;

public class Main {

    private static final Logger log = Logger.getLogger(Main.class);
    private static Main instance;

    private Component component;
    private final StartupOptions startupOptions;

    public Main(StartupOptions startupOptions) {
        this.startupOptions = startupOptions;
    }

    public static void main(String[] args) throws Exception {
        instance = new Main(StartupOptions.parse(args));
        new MainThread();
    }

    public void start() throws Exception {
        log.info("Starting restlet server");
        configureRestletLogging();
        stop();
        component = new Component();
        component.getLogService().setEnabled(startupOptions.isHttpLog());
        component.getServers().add(Protocol.HTTP, startupOptions.getHttpPort());
        component.getServers().add(Protocol.FILE);
        component.getClients().add(Protocol.FILE);
        component.getDefaultHost().attach(new ReplicationServerApplication(component.getContext(), startupOptions));
        component.start();
        log.info("Started restlet server");
    }

    private void configureRestletLogging() {
        java.util.logging.Logger.getLogger("com.noelios").setLevel(Level.SEVERE);
        java.util.logging.Logger.getLogger("org.restlet").setLevel(Level.SEVERE);
    }

    public void stop() throws Exception {
        if (component != null) {
            log.info("Stopping restlet server");
            component.stop();
            log.info("Stopped restlet server");
        }
    }

    public void restart() throws Exception {
        log.info("Restarting restlet server");
        stop();
        start();
    }

    public static Main getInstance() {
        return instance;
    }

    public static class MainThread extends Thread {

        public MainThread() {
            super();
            setDaemon(false);
            start();
        }

        @Override
        public void run() {
            try {
                instance.start();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
}
